public class TheradDemoVolatile {
    private static boolean flag = false;
    public static void main(String[] args){
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程1 开始执行");
                while (!flag) {

                }
                System.out.println("终⽌执⾏");
            }
        });
        t1.start();
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("在线程2 中设置 flag=true");
                flag = true;
            }
        });
        t2.start();
    }
}

